package org.dy.upload;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.fileupload.FileItem;

public class MultipartFormBean {

	private List<FileItem> itemList = new ArrayList<FileItem>();

	private Map fields;

	public Map getFields() {
		return fields;
	}

	public void setFields(Map fields) {
		this.fields = fields;
	}

	public String getFieldValue(String fieldName) {
		if (fields == null || fieldName == null)
			return null;
		return (String) fields.get(fieldName);
	}

	public int getFieldIntValue(String fieldName) {
		String v = getFieldValue(fieldName);
		return v == null ? -1 : Integer.parseInt(v);
	}

	public FileItem getItem(String fieldName) {
		for (FileItem item : itemList) {
			if (item.getFieldName().equals(fieldName))
				return item;
		}
		return null;
	}

	public FormFileBean getOne(String fieldName) {
		FileItem item = getItem(fieldName);

		if (item == null)
			return null;

		FormFileBean resultBean = new FormFileBean();

		if (item != null) {
			String fileNameLong = item.getName();
			fileNameLong = fileNameLong.replace('\\', '/');
			String[] pathParts = fileNameLong.split("/");
			String tfileName = pathParts[pathParts.length - 1];

			resultBean.setContentType(item.getContentType());
			resultBean.setBinary(item.get());
			resultBean.setFileName(tfileName);
			resultBean.setFilePath(fileNameLong);
		}

		return resultBean;
	}

	public String getFileName(FileItem item) {
		if (item != null) {
			String fileNameLong = item.getName();
			fileNameLong = fileNameLong.replace('\\', '/');
			String[] pathParts = fileNameLong.split("/");
			String tfileName = pathParts[pathParts.length - 1];

			return tfileName;
		}
		return null;
	}

	public void addFileItem(FileItem item) {
		this.itemList.add(item);
	}

	public List<FileItem> getItemList() {
		return itemList;
	}
}
